//
//  NoNaviWebViewController.m
//  KidReading
//
//  Created by linziyuan on 2017/5/16.
//  Copyright © 2017年 刘赞黄Telen. All rights reserved.
//

#import "NoNaviWebViewController.h"
#import "ConstDefine.h"

@interface NoNaviWebViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIImageView *bgView;
//
@property (nonatomic, strong) UIView *closeView;

@property (nonatomic, strong) ZYLoadingProgress *loadingView;

@end

@implementation NoNaviWebViewController
{
    NSDictionary *_titleBarDic;
    //
    BOOL _isPhone;
    UIImageView *bView;
    
}
static NoNaviWebViewController* currentWebVC = nil;
+ (instancetype)currentWebVCInstance
{
    return currentWebVC;
}

-(void)hurdleShareSuccessReflshWebView{
    NSString * strJS = @"finishCallback()";
    [_webView stringByEvaluatingJavaScriptFromString:strJS];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.contentView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.edges.JRMAS_equalTo(0);
    }];
    //
    currentWebVC = self;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        _isPhone = YES;
    }else {
        _isPhone = NO;
    }
    bView = [[UIImageView alloc] init];
    [self.contentView addSubview:bView];
    [bView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.edges.equalTo(self.contentView);
    }];
    bView.backgroundColor = [UIColor colorWithHexString:@"#EDEEF4"];
    [self initialUI];
    [self loadRequest];
    //self.title = [NSString stringWithFormat:@"WebView_%@", self.url];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self forceToOrientation:UIInterfaceOrientationPortrait];
    currentWebVC = self;
    [[RootViewController shareLastInstance] stopAudioPlay:NO];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.countActivity.hidden = YES;
    if (self.statisticType == StatisticType_poetry) {
       [NSObject msgToClassName:@"TLMobStat" menthed:@"eventStart:eventLabel:" refs:@[PC_main,PC_main] needReturnValue:NO];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (self.statisticType == StatisticType_poetry) {
        [NSObject msgToClassName:@"TLMobStat" menthed:@"eventEnd:eventLabel:" refs:@[PC_main,PC_main] needReturnValue:NO];
    }
}

- (void)initialUI {
    
    __weak NoNaviWebViewController *wself = self;
    self.bgView = [[UIImageView alloc] init];
    self.bgView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:self.bgView];
    [self.bgView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.top.equalTo(wself.view);
        make.left.right.bottom.equalTo(self.contentView);
    }];

    self.webView = [self getAnWebView];
    CGFloat topOff = 0;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        topOff = 20/ratio_h;
    }
    CGFloat btnLeg = 44.0/ratio_h;
    CGFloat btnPadding = 16.0/ratio_h;
    self.closeView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.contentView addSubview:self.closeView];
    [self.closeView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.size.JRMAS_equalTo(CGSizeMake(btnLeg+btnPadding, btnLeg+btnPadding));
        make.top.equalTo(wself.contentView).offset(topOff);
        make.left.equalTo(wself.contentView);
    }];
    UIImageView *closeImgV = [[UIImageView alloc] initWithFrame:CGRectZero];
    closeImgV.image = [UIImage imageNamed:@"close_btn_web.png"];
    [self.closeView addSubview:closeImgV];
    [closeImgV JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.center.equalTo(wself.closeView);
        make.size.JRMAS_equalTo(CGSizeMake(btnLeg, btnLeg));
    }];
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.closeView addSubview:closeBtn];
    [closeBtn JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.edges.equalTo(wself.closeView);
    }];
    [closeBtn addTouchScaleTransitions_forView:closeImgV];
    [closeBtn addTarget:self action:@selector(closeClick:) forControlEvents:UIControlEventTouchUpInside];
    
    CGFloat loadingHeight = 8/[DataProcessing shareSingle].ratio_h;
    self.loadingView = [ZYLoadingProgress new];
    self.loadingView.colorMove = NO;
    self.loadingView.colors = @[[[UIColor colorWithHexString:@"#727CCA"] colorWithAlphaComponent:0.1],[UIColor colorWithHexString:@"#727CCA"] ,[UIColor colorWithHexString:@"#727CCA"]];
    [self.view addSubview:self.loadingView];
    [self.loadingView JRMAS_remakeConstraints:^(JRMASConstraintMaker *make) {
        make.left.right.equalTo(self.contentView);
        make.height.equalTo(@(loadingHeight));
        make.top.equalTo(wself.view).offset(0);
    }];
}

- (void)closeClick:(id)sender {
    [JSDataProcessing cancelAllLocalActions];
    if (self.showType == SettingShowType_Quiz) {
        [[DBHelper shareInstance] readInfo_Dicts_sendToNet];
        if (self.popUpType == WebPopUpType_Push) {
            [self.navigationController popViewControllerAnimated:YES];
        }else if (self.popUpType == WebPopUpType_Present){
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        if (currentWebVC == self) {
            currentWebVC = nil;
        }
    }
    [self.webView stopLoading];
    if (self.popUpType == WebPopUpType_Push) {
        [self.navigationController popViewControllerAnimated:YES];
    }else if (self.popUpType == WebPopUpType_Present){
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    if (currentWebVC == self) {
        currentWebVC = nil;
    }
}

- (void)shareWithUrl:(NSString *)url {
    /*
     desc = "\U53c2\U52a0\U4e86WaWaYaYa\U7231\U8bfb\U7684\U7ed8\U672c\U521b\U4f5c\U5927\U8d5b\Uff0c\U5feb\U6765\U7ed9TA\U6295\U7968\U5427\Uff01";
     img = "http://aidu.wawayaya.com/Files/BookImages/41460/zbxy130114-953460e5-2d1c-47ea-862e-b98f85a256db-0.jpg?stamp=1456631511719";
     model = share;
     title = "\U7684\U7ed8\U672c\U4f5c\U54c1";
     value = "http://10.135.195.150:9797/apiweb/bookarticle/getBookArticleShare?bookId=1157&activityId=1&userId=10990";
     */
    NSString *shareImg = [_titleBarDic valueForKey:@"img"];
    NSString *shareTitle = [_titleBarDic valueForKey:@"title"];
    NSString *shareDes = [_titleBarDic valueForKey:@"desc"];
    
    NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
    NSArray *iconArr = [infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"];
    NSString *icon = [iconArr lastObject];
    if ([DataProcessing iOS7_low]) {
        if (iconArr.count>1) {
            icon = iconArr[1];
        }
        
    }
    UIImage *imgicon = [UIImage imageNamed:icon];
    id img = imgicon;
    if (shareImg.length > 0) {
        img = shareImg;
    }
    NSString *title = NSLocalizedString(@"sharetitle", nil);
    if (shareTitle.length>0) {
        title = shareTitle;
    }
    NSString *text = NSLocalizedString(@"sharetext", nil);
    if (shareDes.length > 0) {
        text = shareDes;
    }
    
    NSArray* imageArray = @[img];
    if (imageArray) {
        [[ShareManager shareManager] JRShareWithText:text ImageArray:imageArray Url:[NSURL URLWithString:url] Title:title Type:SSDKContentTypeAuto BaseView:self.webView statusChange:^(SSDKResponseState state, SSDKPlatformType type) {
            if (state == SSDKResponseStateBegin) {
                [[WaWaYaYaRewardManager defaultManager] logRewardEventIsNeedHandle:YES ActCode:ActCode_WebShareSuccess Param:nil];
            }
        }];
    }
}



- (UIWebView *)exchangeWebView
{
    UIWebView* wbview = [self getAnWebView];
    [self.webView.superview insertSubview:wbview belowSubview:self.webView];
    [self.webView stopLoading];
    [self.webView removeFromSuperview];
    self.webView = wbview;
    //
    return wbview;
}

- (UIWebView *)getAnWebView {
    
    __weak NoNaviWebViewController *wself = self;
    CGFloat hpadding = 20.0;
    CGFloat pPadding = 30.0;
    if (_isPhone) {
        hpadding = 15.0;
        pPadding = 20.0;
    }
    if (self.isfullScrean) {
        hpadding = 0;
        pPadding = 0;
        if (_isPhone) {
            pPadding = 20.0/ratio_h;
        }
    }
    UIWebView *webV = [[UIWebView alloc] init];
    webV.mediaPlaybackRequiresUserAction = NO;
    webV.allowsInlineMediaPlayback = YES;
    webV.delegate = self;
    [self.contentView addSubview:webV];
    [webV JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.top.equalTo(wself.view).offset(pPadding);
        make.left.equalTo(wself.contentView).offset(pPadding);
        make.right.equalTo(wself.contentView).offset(-pPadding);
        make.bottom.equalTo(wself.contentView).offset(-hpadding);
    }];
    
    webV.backgroundColor = [UIColor clearColor];
    //self.webView.paginationMode = UIWebPaginationModeTopToBottom;
    webV.scrollView.showsVerticalScrollIndicator = NO;
    webV.scrollView.showsHorizontalScrollIndicator = NO;
    
    if (self.clear_Bg) {
        [webV setOpaque:NO];
        webV.backgroundColor = [UIColor clearColor];
        webV.paginationMode = UIWebPaginationModeUnpaginated;
        webV.backgroundColor = [UIColor clearColor];
    }else{
        [webV setOpaque:YES];
        webV.backgroundColor = [UIColor clearColor];
        //self.webView .paginationMode = UIWebPaginationModeTopToBottom;//从上而下
        webV.backgroundColor = [UIColor whiteColor];
    }
    return webV;
}

- (void)loadRequest{
    if (self.showType == SettingShowType_Local) {
        //self.titleLabel.text = NSLocalizedString(@"canNotLinkNet", nil);
        NSString *filePath = [[NSBundle mainBundle]pathForResource:[DataProcessing chooseLanguageFromCN:@"localFiles.bundle/network_available_cn" andEN:@"localFiles.bundle/network_available_en"] ofType:@"html"];
        NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        [self.webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
    }
    if (self.url) {
        if (self.showType == SettingShowType_H5) {
            NSString *url = [NetRequest netFullUrl_Get:self.url fromDict:[[NetRequestWithCache_JR shareSingle] netRequestAddBaseInfo:self.otherParas]];
#ifdef __Debug_JSLog
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
#else
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
#endif
            [self.webView loadRequest:request];
        }
        else if (self.showType == SettingShowType_contact || self.showType == SettingShowType_normalLink) {
#ifdef __Debug_JSLog
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
#else
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
#endif
            [self.webView loadRequest:request];
        }
        else if (self.showType == SettingShowType_Quiz) {
            
#ifdef __Debug_JSLog
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
#else
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
#endif
            [self.webView loadRequest:request];
        }
        else {
            [[NetRequest shareSingle] webViewAskNet:self.url andBaseUrl:__Ser3_0_URL_Base_ parameters:@{} success:^(NSData *retData) {
                if (retData) {
                    [self.webView loadData:retData MIMEType:@"text/html"  textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:self.url]];
                }else {
                    [self showEmptyViewWithType:EmptyShowType_Web tapEnabel:YES];
                }
            } failure:^(NSError *error) {
                [self showEmptyViewWithType:EmptyShowType_Web tapEnabel:YES];
                //[self showEmptyForWeb];
            }];
        }
    }
}

- (void)showEmptyViewWithType:(EmptyShowType)type tapEnabel:(BOOL)tapenable{
    self.bgView.hidden = YES;
    bView.hidden = YES;
    [self.emptyShow emptyShowWithType:type tapEnabel:tapenable hideView:self.webView defineStr:nil];
}

- (void)tapEmptyShow {
    self.bgView.hidden = NO;
    bView.hidden = NO;
    [self loadRequest];
    [self.emptyShow dismissEmptyShowView:self.webView];
}

- (void)hideCloseBtn {
    self.closeView.hidden = YES;
}

#pragma mark WebView Delegate

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [self.loadingView startAnimating];
    if (self.showType == SettingShowType_H5 || self.showType == SettingShowType_normalLink) {

    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (self.showType == SettingShowType_Quiz) {
        NSString* url = request.URL.absoluteString;
        NSArray* arr = [url componentsSeparatedByString:@"?"];
        NSString* urlbase = arr.firstObject;
        if ([urlbase hasSuffix:@"/quizdata.html"] && arr.count == 2) {
            NSString* str = arr[1];
            NSDictionary* refDict = [self dicTogetRef:str];
            str = refDict[@"data"];
            str = [str URLDecodedString];
            NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSError* error = nil;
            NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            if (dict) {
                [[DBHelper shareInstance] addQuizInfoWithQuizDict:dict];
            }
        }
        NSString *titleStr = [JSDataProcessing quizTitleWithUrl:url];
        if (titleStr.length) {
            titleStr = [titleStr URLDecodedString];
            //self.titleLabel.text = titleStr;
        }
        //NSString *rightStr = [JSDataProcessing quizRightTitleWithUrl:url];
        //if (rightStr.length) {
//        rightStr = [rightStr URLDecodedString];
//        self.quizRLabel.text = rightStr;
        //}
        [JSDataProcessing startURL:request.URL.absoluteString webView:self.webView currentVC:self];
        if ([request.URL.absoluteString hasPrefix:@"localcall::"]) {
            return NO;
        }
    }
    if (webView.newWebView) {
        webView = [self exchangeWebView];
        [webView loadRequest:request];
        return NO;
    }else {
        //[self.indicator startAnimating];
        if(self.isClickToBrower && navigationType == UIWebViewNavigationTypeLinkClicked){
            [[UIApplication sharedApplication] openURL:request.URL];
            return NO;
        }
        [JSDataProcessing startURL:request.URL.absoluteString webView:self.webView currentVC:self];
        if ([request.URL.absoluteString hasPrefix:@"localcall::"]) {
            return NO;
        }
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [self.loadingView stopAnimating];
    //[self.indicator stopAnimating];
    //[self.emptyShow dismissEmptyShowView:self.webView];
    if (self.claar_DeviceWith) {
        [JSDataProcessing reg_poptool_js:self.webView];
        [JSDataProcessing js_poptool_clean_device_width:self.webView];
    }
    
    if (self.showType == SettingShowType_H5 || self.showType == SettingShowType_normalLink) {
        
        if (self.showType == SettingShowType_H5) {
            _titleBarDic = [JSDataProcessing titleBarRightInfo:webView];
        }
//        self.titleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
        //[self logJS];
    }
    [JSDataProcessing setUinfoCallback:webView];
}
//
-(void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_USEC), dispatch_get_main_queue(),
                   ^
                   { [super presentViewController:viewControllerToPresent animated:flag completion:completion]; }
                   );
}
//
- (void)logJS {
    NSString *lJs = @"document.documentElement.innerHTML";
    NSString *lHtml = [self.webView stringByEvaluatingJavaScriptFromString:lJs];
    NSLog(@"%@",lHtml);
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    //[self showEmptyViewWithType:EmptyShowType_Defualt];
    [self.loadingView stopAnimating];
    //[self.indicator stopAnimating];
    if (self.showType == SettingShowType_H5) {
        //NSLog(@"self's url ------%@,webview's url -------%@",self.url,webView.request.URL.absoluteString);
        _titleBarDic = [JSDataProcessing titleBarRightInfo:webView];
//        if (error.code != 101 ) {
//            self.titleLabel.text = @"";
//        }
        //[self refreshbar];
        if (error.code != 101 && error.code != (-999)) {    //101 can't be shown
            if (self.url.length>0) {
                [self showEmptyViewWithType:EmptyShowType_Web tapEnabel:YES];
            }else {
                [self showEmptyViewWithType:EmptyShowType_Defualt tapEnabel:NO];
            }
        }
    }else if (self.showType == SettingShowType_normalLink) {
        if (error.code != 101 ) {
            //self.titleLabel.text = @"";
        }
    }
}

- (NSDictionary*)dicTogetRef:(NSString*)refStr
{
    if (refStr) {
        NSMutableDictionary* mdic = [NSMutableDictionary new];
        NSArray* arr = [refStr componentsSeparatedByString:@"&"];
        for (NSString* str in arr) {
            NSArray* kvs = [str componentsSeparatedByString:@"="];
            if (kvs.count == 2) {
                [mdic setObject:kvs[1] forKey:kvs[0]];
            }
        }
        return mdic;
    }
    return nil;
}

- (UIView *)shareTrackView {
    return self.loadingView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
